package com.ajview.core.config;

import com.ajview.common.utils.ThreadUtils;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * PROJECT_NAME: 线程池配置
 *
 * @DESCRIPTION: 线程池配置
 * @DATE 2022-12-21 上午 12:05
 * @Author zhangjunjie
 */
@Configuration
public class ThreadPoolConfig {
    /**
     * 核心线程池大小
     */
    private int corePoolSize = 50;

    /**
     * 最大可创建的线程数
     */
    private int maxPoolSize = 200;

    /**
     * 队列最大长度
     */
    private int queueCapacity = 1000;

    /**
     * 线程池维护线程所允许的空闲时间
     */
    private int keepAliveSeconds = 300;

    /**
     * 线程池的前缀名称
     */
    private String threadNamePrefix = "ajview-core-task-";


    /**
     * 配置Spring 线程池
     *
     * @return
     */
    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(maxPoolSize);
        executor.setCorePoolSize(corePoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(threadNamePrefix);
        /**
         * 线程池对拒绝任务(无线程可用)的处理策略
         * CallerRunsPolicy()：交由调用方线程运行，比如 main 线程。
         * AbortPolicy()：直接抛出异常。
         * DiscardPolicy()：直接丢弃。
         * DiscardOldestPolicy()：丢弃队列中最老的任务。
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

    /**
     * 定时任务线程池 执行周期性或定时任务
     *
     * @return
     */
    @Bean(name = "scheduledExecutorService")
    public ScheduledExecutorService scheduledExecutorService() {
        /**
         * 1. corePoolSize：核心工作的线程数量
         * 2. threadFactory：线程工厂，用来创建线程
         * 3. handler: 拒绝策略，饱和策略
         */
        return new ScheduledThreadPoolExecutor(
                corePoolSize, new BasicThreadFactory.Builder().namingPattern(threadNamePrefix + "%d").build(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        ) {
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                // 打印线程异常日志
                ThreadUtils.printException(r, t);
            }
        };
    }


}
